package com.neusoft.tijiancms.datastruc;

public class DataArray {
    //创建数组
    private int[] intArray;
    //数组中元素的实际有效长度
    private int elems;
    //数组中的最大长度
    private int length;

    //将以上属性初始化
    public DataArray() {
        this.elems = 0;
        this.length = 50;
        this.intArray = new int[length];
    }

    //将以上属性初始化
    public DataArray(int length) {
        this.elems = 0;
        this.length = length;
        this.intArray = new int[length];
    }

    //遍历数组元素
    public void display() {
        for(int i = 0;i<elems;i++) {
            System.out.println(intArray[i] + " ");
        }
    }

    //添加元素
    public boolean add(int value) {
        if(elems == length) {
            return false;
        }else {
            intArray[elems] = value;
            elems++;
        }
        return true;
    }

    //根据下标获取某个元素
    public int get(int i) {
        if(i < 0 || i > elems) {
            System.out.println("数组下标越界......");
        }
        return intArray[i];
    }

    //查找元素(如果要查找的元素存在返回下标值，如果不存在返回-1)
    public int find(int searchValue) {
        int i ;
        for(i = 0 ; i < elems ;i++){
            if(intArray[i] == searchValue){
                break;
            }
        }
        if(i == elems){
            return -1;
        }
        return i;
    }

    //修改元素
    public boolean modify(int oldValue,int newValue) {
        int i = find(oldValue);
        if(i == -1){
            System.out.println("需要修改的数据不存在");
            return false;
        }else{
            intArray[i] = newValue;
            return true;
        }
    }

    public static void main(String[] args) {
        DataArray dataArray = new DataArray(4);
        dataArray.add(1);
        dataArray.add(2);
        dataArray.add(3);
        dataArray.display();
        System.out.println(dataArray.find(3));
        dataArray.modify(3,4);
        dataArray.display();
    }






}
